<?php
if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );

/**
*
* @package  RealEstateManager
* @copyright 2011 Andrey Kvasnevskiy-OrdaSoft(akbet@mail.ru); Rob de Cleen(rob@decleen.com); Sergey Drughinin (Sergey.dru@gmail.com) ; 
* Homepage: http://www.joomlawebserver.com
* @version: 2.1 free $
*
**/

defined( '_VM_IS_BACKEND' ) or define( '_VM_IS_BACKEND', '1' );


include_once( dirname(__FILE__).'/compat.joomla1.5.php' );
include_once( dirname(__FILE__).'/functions.php' );
$my=$GLOBALS['my'];
if (get_magic_quotes_gpc()) {
  function stripslashes_gpc(&$value)
  {
    $value = stripslashes($value);
  }
  array_walk_recursive($_GET, 'stripslashes_gpc');
  array_walk_recursive($_POST, 'stripslashes_gpc');
  array_walk_recursive($_COOKIE, 'stripslashes_gpc');
  array_walk_recursive($_REQUEST, 'stripslashes_gpc');
}

$css = $mosConfig_live_site.'/administrator/components/com_realestatemanager/includes/realestatemanager.css';

// include_once ($mainframe->getPath('admin_html'));
// include_once ($mainframe->getPath('class'));

$mainframe = JFactory::getApplication();

include_once($mosConfig_absolute_path.'/libraries/joomla/html/pagination.php');// for 1.6

require_once ($mosConfig_absolute_path."/administrator/components/com_realestatemanager/admin.realestatemanager.html.php");
require_once($mosConfig_absolute_path."/components/com_realestatemanager/realestatemanager.class.php");
require_once ($mosConfig_absolute_path."/components/com_realestatemanager/realestatemanager.class.rent.php");
require_once ($mosConfig_absolute_path."/components/com_realestatemanager/realestatemanager.class.rent_request.php");
require_once ($mosConfig_absolute_path."/components/com_realestatemanager/realestatemanager.class.buying_request.php");
require_once ($mosConfig_absolute_path."/administrator/components/com_realestatemanager/admin.realestatemanager.class.impexp.php");
require_once ($mosConfig_absolute_path."/administrator/components/com_realestatemanager/admin.realestatemanager.class.conf.php");
require_once ($mosConfig_absolute_path."/administrator/components/com_realestatemanager/functions.php");
require_once ($mosConfig_absolute_path."/components/com_realestatemanager/realestatemanager.main.categories.class.php");



$GLOBALS['realestatemanager_configuration'] = $realestatemanager_configuration;
$GLOBALS['database'] = $database;
$GLOBALS['my'] = $my;
$GLOBALS['mosConfig_absolute_path'] = $mosConfig_absolute_path;
$table_prefix = $database->getPrefix(); // for J 1.6
$GLOBALS['table_prefix'] = $table_prefix; // for J 1.6
$GLOBALS['option'] = $option = trim( mosGetParam( $_REQUEST, 'option', "com_realestatemanager" ) );
$GLOBALS['task'] = $task = trim( mosGetParam( $_REQUEST, 'task', "" ) );

global $mosConfig_lang;

$cls_path = $mosConfig_absolute_path."/components/com_realestatemanager/realestatemanager.class.php" ;
require_once ($cls_path);

// require_once ($mosConfig_absolute_path."/includes/domit/xml_domit_include.php");

// load language
$lang_def_en=0;
$lang =& JFactory::getLanguage();
foreach ($lang->getLocale() as $locale) {
          $mosConfig_lang=$locale;
    if (file_exists($mosConfig_absolute_path."/components/com_realestatemanager/language/{$mosConfig_lang}.php" ))     {  
          include_once($mosConfig_absolute_path."/components/com_realestatemanager/language/{$mosConfig_lang}.php" );
          $lang_def_en=1;
           break;
    } 
}
if ( $lang_def_en != 1 ) {
   $mosConfig_lang = "english";  
   include_once($mosConfig_absolute_path."/components/com_realestatemanager/language/english.php" );
}


$bid = mosGetParam($_POST, 'bid', array (0)); 
$section = mosGetParam( $_REQUEST, 'section', 'courses' );

if($realestatemanager_configuration['debug'] == '1'){

	echo "Task: ".$task . "<br />";

	print_r($_REQUEST);

	echo "<hr /><br />";

}

if (isset($section) && $section=='categories')
{ 
switch ($task){

    case "edit" :
        editCategory($option, $bid[0]);
        break;
    
    case "add":
        editCategory($option, 0);
        break;
    case "cancel":
        cancelCategory();
        break;
    case "save":
        saveCategory();
        break;
    case "remove":
        removeCategories($option, $bid);
        break;
    case "publish":
        publishCategories("com_realestatemanager", $id, $bid, 1);
        break;
    case "unpublish":
        publishCategories("com_realestatemanager", $id, $bid, 0);
        break;
    case "orderup":
        orderCategory($bid[0], -1);
        break;
    case "orderdown":
        orderCategory($bid[0], 1);
        break;
    case "accesspublic":
        accessCategory($bid[0], 0);
        break;
    case "accessregistered":
        accessCategory($bid[0], 1);
        break;
    case "accessspecial":
        accessCategory($bid[0], 2);
        break;
    case "show":
    default :
        showCategories();
}
} 
else 
{

switch ($task) {	

	case "categories":
echo "now work $section=='categories , this part not work"; exit;
	    	mosRedirect( "index.php?option=categories&section=com_realestatemanager" );
	    	break;	

	case "add" :
		editHouse($option, 0);
		break;
       
	case "edit" :
		editHouse($option, array_pop($bid));
		break;

	case "save" :		
		saveHouse($option);
		break;

	case "remove" :
		removeHouses($bid, $option);
		break;

	case "publish" :
		publishHouses($bid, 1, $option);
		break;

	case "unpublish" :
		publishHouses($bid, 0, $option);
		break;

  case "approve" :
      approveHouses($bid, 1, $option);
      break;

  case "unapprove" :
      approveHouses($bid, 0, $option);
      break;
        

	case "cancel" :
		cancelHouse($option);
		break;

	case "houseorderdown" :
		orderHouses($bid[0], 1, $option);
		break;

	case "houseorderup" :
		orderHouses($bid[0], -1, $option);
		break;

  case "config" :
    configure($option);
    break;

	case "config_save" :
		configure_save_frontend($option);
		configure_save_backend($option);
    configure($option);
		break;

	case "rent" :
		if (mosGetParam($_POST, 'save') == 1) {
			saveRent($option, $bid);
		} else{
			rent($option, $bid);
		}
		break;

	case "rent_requests" :
		rent_requests($option, $bid);	
		break;

	case "buying_requests" :
		buying_requests($option);	
		break;	

	case "accept_rent_requests" :
		accept_rent_requests($option, $bid);	
		break;

	case "decline_rent_requests" :
		decline_rent_requests($option, $bid);	
		break;

	case "accept_buying_requests" :
		accept_buying_requests($option, $bid);	
		break;

	case "decline_buying_requests" :
		decline_buying_requests($option, $bid);	
		break;

	case "about" :
		HTML_realestatemanager :: about();
		break;

	case "show_info" :
		showInfo($option, $bid);
		break;

	case "rent_return" :
		if (mosGetParam($_POST, 'save') == 1) {
			saveRent_return($option, $bid);			
		} else {
			rent_return($option, $bid);
		}
		break;
    
  case "edit_rent" :
      if (mosGetParam($_POST, 'save') == 1) {
          if(count($bid) > 1 ) {
            echo "<script> alert('You must select only one item for edit'); window.history.go(-1); </script>\n";
            exit();
          }
          saveRent($option, $bid,"edit_rent");
      } else {
        edit_rent($option, $bid);
      }
      break;

	case "delete_review" :
		$ids = explode(',',$bid[0]);
		delete_review($option, $ids[1]);
		editHouse($option, $ids[0]);
		break;

	case "edit_review" :
		$ids = explode(',',$bid[0]);
		edit_review($option, $ids[1], $ids[0]);
		break;

	case "update_review" :
		$title = mosGetParam($_POST, 'title') ;
		$comment = mosGetParam($_POST, 'comment') ;
		$rating = mosGetParam($_POST, 'rating') ;
		$house_id = mosGetParam($_POST, 'house_id') ;
		$review_id = mosGetParam($_POST, 'review_id') ;

		update_review($title,$comment,$rating,$review_id );
		editHouse($option, $house_id );
		break;
	
	case "cancel_review_edit" :
		$house_id = mosGetParam($_POST, 'house_id') ;
		editHouse($option, $house_id );
		break;

	default :
		showHouses($option);
		break;

}

} //else

class CAT_Utils
{
    function categoryArray()
    {
        global $database;
        // get a list of the menu items
        $query = "SELECT c.*, c.parent_id AS parent"
         . "\n FROM #__rem_main_categories c"
         . "\n WHERE section='com_realestatemanager'"
         . "\n AND published <> -2"
         . "\n ORDER BY ordering" ;
        $database->setQuery($query);
        $items = $database->loadObjectList();        
	// establish the hierarchy of the menu
        $children = array();
        // first pass - collect children
        foreach ($items as $v) {
            $pt = $v->parent;
            $list = @$children[$pt] ? $children[$pt] : array();
            array_push($list, $v);
            $children[$pt] = $list;
        }
        // second pass - get an indent list of the items
        $array = mosTreeRecurse(0, '', array(), $children);

        return $array;
    }

}



/**
* HTML Class
* Utility class for all HTML drawing classes
* @desc class General HTML creation class. We use it for back/front ends.
*/
class HTML
{
    // TODO :: merge categoryList and categoryParentList
    // add filter option ?
    function categoryList($id, $action, $options = array())
    {
        $list = CAT_Utils::categoryArray();
        // assemble menu items to the array
        foreach ($list as $item) {
            $options[] = mosHTML::makeOption($item->id, $item->treename);
        }
        $parent = mosHTML::selectList($options, 'catid', 'id="catid" class="inputbox" size="1" onchange="' . $action . '"', 'value', 'text', $id);
        return $parent;
    }

	function categoryParentList($id, $action, $options = array())
	{
                global  $database;
                $list = CAT_Utils::categoryArray();
                $cat = new mainRealEstateCategories($database);//for 1.6
                $cat->load($id);
  
                $this_treename = '';
                $childs_ids =  Array();
                foreach ($list as $item) {
                  if ($item->id == $cat->id || array_key_exists($item->parent_id,$childs_ids) ) 
                  $childs_ids[$item->id] = $item->id;
                }
                
                foreach ($list as $item) {
                        if ($this_treename) {
                                if ($item->id != $cat->id 
                                  && strpos($item->treename, $this_treename) === false
                                  && array_key_exists($item->id,$childs_ids) === false) {
                                        $options[] = mosHTML::makeOption($item->id, $item->treename);
                                }
                        } else {
                                if ($item->id != $cat->id) {
                                        $options[] = mosHTML::makeOption($item->id, $item->treename);
                                } else {
                                        $this_treename = "$item->treename/";
                                }
                        }
                }
  
                $parent= null;
                  $parent = mosHTML::selectList($options, 'parent_id', 
                    'class="inputbox" size="1"', 'value', 'text', $cat->parent_id);
  
                return $parent;
	}






function imageList($name, &$active, $javascript = null, $directory = null)
 {
  
  global $mosConfig_absolute_path;
  if (!$javascript) 
  {
    $javascript = "onchange=\"javascript:if (document.adminForm." . $name .
      ".options[selectedIndex].value!='')    {document.imagelib.src='../images/stories/' + document.adminForm."
      . $name . ".options[selectedIndex].value} else {document.imagelib.src='../images/blank.png'}\"";
  }
  if (!$directory) {
      $directory = '/images/stories';
  }

  if ( !file_exists($mosConfig_absolute_path.$directory)) {
    @mkdir($mosConfig_absolute_path.$directory, 0777) or die("Error of directory creating: [".$mosConfig_absolute_path.$directory."] ");
  }

  $imageFiles = mosReadDirectory($mosConfig_absolute_path.$directory);
  $images = array(mosHTML::makeOption('', _A_SELECT_IMAGE));
  foreach ($imageFiles as $file) {
      if (preg_match("/bmp|gif|jpg|png/i", $file)) {
          $images[] = mosHTML::makeOption($file);
    }
  }

  $images = mosHTML::selectList($images, $name, 'id="'.$name.'" class="inputbox" size="1" ' . $javascript, 'value', 'text',   $active);
  return $images;
  }
}






function houseLibraryTreeRecurse( $id, $indent, $list, &$children, $maxlevel=9999, $level=0, $type=1 ) {

	if (@$children[$id] && $level <= $maxlevel) {
	    $parent_id = $id;
		foreach ($children[$id] as $v) {
			$id = $v->id;

			if ( $type ) {
				$pre 	= 'L ';
				$spacer = '.      ';
			} else {
				$pre 	= '- ';
				$spacer = '  ';
			}

			if ( $v->parent == 0 ) {
				$txt 	= $v->name;
			} else {
				$txt 	= $pre . $v->name;
			}
			$pt = $v->parent;
			$list[$id] = $v;
			$list[$id]->treename = "$indent$txt";
			$list[$id]->children = count( @$children[$id] );
    		$list[$id]->all_fields_in_list = count(@$children[$parent_id]);

			$list = houseLibraryTreeRecurse( $id, $indent . $spacer, $list, $children, $maxlevel, $level+1, $type );
		}
	}
	return $list;
}

function showCategories()
{
    global $database, $my, $acl, $option, $menutype, $mainframe, $mosConfig_list_limit;
    $mainframe = JFactory::getApplication();

    $grooups['-2'] = ('Everyone');

    $query = 'SELECT `id`,`title` FROM #__usergroups';
    $database->setQuery($query);
    $rows = $database->loadObjectList();
    foreach ($rows as $k => $v) {
      $id_group = $rows[$k]->id;
      $group_name = $rows[$k]->title;

      $grooups[$id_group] = $group_name;
    }
    $section = "com_realestatemanager";

    $sectionid = $mainframe->getUserStateFromRequest("sectionid{$section}{$section}", 'sectionid', 0);
    $limit = $mainframe->getUserStateFromRequest("viewlistlimit", 'limit', $mosConfig_list_limit);
    $limitstart = $mainframe->getUserStateFromRequest("view{$section}limitstart", 'limitstart', 0);
    $levellimit = $mainframe->getUserStateFromRequest("view{$option}limit$menutype", 'levellimit', 10);

    $query = "SELECT  c.*, c.checked_out as checked_out_contact_category, "
     . " c.parent_id as parent, u.name AS editor, c.params, COUNT(hc.id) AS cc"
     . "\n FROM #__rem_main_categories AS c"
     . "\n LEFT JOIN #__rem_categories AS hc ON hc.idcat=c.id"
     . "\n LEFT JOIN #__users AS u ON u.id = c.checked_out"
     . "\n WHERE c.section='$section'"
     . "\n GROUP BY c.id"
     . "\n ORDER BY parent DESC, ordering" ;
     
    $database->setQuery($query);
    $rows = $database->loadObjectList();

    if ($database->getErrorNum()) {
        echo $database->stderr();
        return false;
    } 
    
//echo "<pre>"; print_r($cat_all2); echo "</pre>";exit;
    foreach ($rows as $k => $v) {
        $rows[$k]->ncourses = 0;
        foreach ($rows as $k1 => $v1) {
            if ($v->id == $v1->parent)
                $rows[$k]->cc +=$v1->cc;
        }
//          $rows[$k]->nhouse = ($aa == 0) ? "-" : "<a href=\"?option=com_realestatemanager&section=house&catid=" . $v->id . "\">" . ($aa) . "</a>";
        ($rows[$k]->cc==0)?"-":"<a href=\"?option=com_realestatemanager&section=house&catid=".$v->id."\">".($v->cc)."</a>";//for 1.6
        $curgroup = "";
        $ss = explode(',', $v->params);
        foreach ($ss as $s) {
            if ($s == '')
                $s = '-2';
            $curgroup[] = $grooups[$s];
        }
        $rows[$k]->groups = implode(', ', $curgroup);
    }

    if ($database->getErrorNum()) {
      echo $database->stderr();
      return false;
    }

    // establish the hierarchy of the categories
    $children = array(); 
    // first pass - collect children
    foreach ($rows as $v) {
        $pt = $v->parent;
        $list = @$children[$pt] ? $children[$pt] : array();
        array_push($list, $v);
        $children[$pt] = $list;
    } 
    // second pass - get an indent list of the items
    $list = houseLibraryTreeRecurse(0, '', array(), $children, max(0, $levellimit-1));
    $total = count($list);

    $pageNav = new JPagination( $total, $limitstart, $limit ); // for J 1.6

    $levellist = mosHTML::integerSelectList(1, 20, 1, 'levellimit', 'size="1" onchange="document.adminForm.submit();"', $levellimit); 
    // slice out elements based on limits
    $list = array_slice($list, $pageNav->limitstart, $pageNav->limit);


    $count = count($list); 

    $javascript = 'onchange="document.adminForm.submit();"';

    //$lists['sectionid'] = mosAdminMenus::SelectSection('sectionid', $sectionid, $javascript);

    HTML_Categories::show($list, $my->id, $pageNav, $lists, 'other');
}





function editCategory($section = '', $uid = 0)
{

    global $database, $my,$acl;
    global $mosConfig_absolute_path, $mosConfig_live_site;

    // -- Analogue of get_group_children_tree() for J 1.6 
    $group_children_tree = array (); 
    // -- v.2 
    include_once($mosConfig_absolute_path.'/administrator/components/com_users/models/groups.php'); // for J 1.6

    $model = &JModel::getInstance('Groups', 'UsersModel', array('ignore_request' => true));
    foreach ($g = $model->getItems() as $k => $v) { // $g contains basic usergroup items info
      $group_title = '.';
      for ($i=1; $i<=$g[$k]->level; $i++) {
        $group_title .= '-';}
      $group_title .= '-'.$g[$k]->title;    
      $group_children_tree[] = mosHTML :: makeOption($g[$k]->id, $group_title);
    }

    $type = mosGetParam($_REQUEST, 'type', '');
    $redirect = mosGetParam($_POST, 'section', '');;
    $row = new mainRealEstateCategories($database);	
    // load the row from the db table
    $row->load($uid); 
    // fail if checked out not by 'me'
    if ($row->checked_out && $row->checked_out <> $my->id) {
        mosRedirect('index.php?option=com_realestatemanager&task=categories', 'The category ' . $row->title . ' is currently being edited by another administrator');
    } 

    if ($uid) {
        // existing record
        $row->checkout($my->id); 
        // code for Link Menu
    } else {
        // new record
        $row->section = $section;
        $row->published = 1;
    } 
    // make order list
    $order = array();

    $database->setQuery("SELECT COUNT(*) FROM #__rem_main_categories WHERE section='$row->section'");
    $max = intval($database->loadResult()) + 1;

    for ($i = 1; $i < $max; $i++) {
        $order[] = mosHTML::makeOption($i);
    } 
    // build the html select list for ordering
    $query = "SELECT ordering AS value, title AS text"
     . "\n FROM #__rem_main_categories"
     . "\n WHERE section = '$row->section'"
     . "\n ORDER BY ordering" ;

    $lists['ordering'] = mosAdminMenus::SpecificOrdering($row, $uid, $query);
    // build the select list for the image positions
    $active = ($row->image_position ? $row->image_position : 'left');
    $lists['image_position'] = mosAdminMenus::Positions('image_position', $active, null, 0, 0); 
    // Imagelist
    $lists['image'] = HTML::imageList('image', $row->image); 
    // build the html select list for the group access
    $lists['access'] = mosAdminMenus::Access($row); 
    // build the html radio buttons for published
    $lists['published'] = mosHTML::yesnoRadioList('published', 'class="inputbox"', $row->published); 
    // build the html select list for paraent item
    $options = array();
    $options[] = mosHTML::makeOption('0', _A_SELECT_TOP);

    $lists['parent'] = HTML::categoryParentList($row->id, "", $options);

    //***********access category
    $gtree[] = mosHTML :: makeOption('-2', 'Everyone');
    $gtree = array_merge ( $gtree, $group_children_tree);
    $f = "";
    if(trim($row->params)=='') $row->params='-2';
    $s = explode(',', $row->params); 
    for ($i = 0; $i < count($s); $i++)
        $f[] = mosHTML::makeOption($s[$i]);
    $lists['category']['registrationlevel'] = mosHTML::selectList($gtree, 'category_registrationlevel[]', 'size="" multiple="multiple"', 'value', 'text', $f);
    //********end access category

    HTML_Categories::edit($row, $section, $lists, $redirect);
}








function saveCategory()
{
    global $database;

    $row = new mainRealEstateCategories($database);
//     $post = JRequest::get('post',JREQUEST_ALLOWHTML);
    if (!$row->bind($_POST)) {
        echo "<script> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
        exit();
    } 
    $row->section='com_realestatemanager'; 
    $row->parent_id=$_REQUEST['parent_id'];

    //****set access level
    $row->params = "-2";
  //****end set access level

    if (!$row->check()) {
        echo "<script> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
        exit();
    }
 
    //remove escaped slashes
    if(get_magic_quotes_gpc()) {
      $row->description = stripslashes($row->description);
    }

    if (!$row->store()) {
        echo "<script> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
        exit();
    } 

    $row->checkin();
    $row->updateOrder("section='com_realestatemanager' AND parent_id='$row->parent_id'");

    if ($oldtitle = mosGetParam($_POST, 'oldtitle', null)) {
        if ($oldtitle != $row->title) {
             $database->setQuery("UPDATE #__rem_main_categories " . "\n SET name='$row->title' " . "\n WHERE name='$oldtitle' " . "\n    AND section='com_realestatemanager'");

            $database->query();
        } 
    } 
    mosRedirect('index.php?option=com_realestatemanager&section=categories');
} 

//this function check - is exist houses in this folder and folders under this category 
function is_exist_curr_and_subcategory_houses($catid) {
    global $database, $my; 
    
		$query = "SELECT *, COUNT(a.id) AS numlinks FROM #__rem_main_categories AS cc" 
      . "\n  JOIN #__rem_categories AS hc ON hc.idcat = cc.id"
			. "\n  JOIN #__rem_houses AS a ON a.id = hc.iditem" 
			. "\n WHERE  section='com_realestatemanager' AND cc.id='$catid' " 
			. "\n GROUP BY cc.id" 
			. "\n ORDER BY cc.ordering"; 
    $database->setQuery( $query ); 
    $categories = $database->loadObjectList();
    if( count($categories) != 0 ) return true;

    $query = "SELECT id " 
      . "FROM #__rem_main_categories AS cc " 
      . " WHERE section='com_realestatemanager' AND parent_id='$catid' "; 
    $database->setQuery( $query ); 
    $categories = $database->loadObjectList();
 
    if( count($categories) == 0 ) return false;

    foreach($categories as $k) {
      if( is_exist_curr_and_subcategory_houses($k->id) ) return true;
    }
    return false; 
}//end function

function removeCategoriesFromDB($cid){
    global $database, $my; 

    $query = "SELECT id  " 
      . " FROM #__rem_main_categories AS cc " 
      . " WHERE section='com_realestatemanager' AND parent_id='$cid' "; 
    $database->setQuery( $query ); 
    $categories = $database->loadObjectList();
    //    echo $database->getErrorMsg() ;

    if( count($categories) != 0 ) {
      //delete child
      foreach($categories as $k) {
        removeCategoriesFromDB($k->id) ;
      }
    }

    $sql="DELETE FROM #__rem_main_categories WHERE id = $cid ";
    $database->setQuery($sql);
    $database->query();

}


/**
* Deletes one or more categories from the categories table
* 
* @param string $ The name of the category section
* @param array $ An array of unique category id numbers
*/
function removeCategories($section, $cid)

{
    global $database;

    if (count($cid) < 1) {
        echo "<script> alert('Select a category to delete'); window.history.go(-1);</script>\n";
        exit;
    } 

    foreach ($cid as $catid) {
      if(is_exist_curr_and_subcategory_houses( $catid  ) ){
        echo "<script> alert('Some category or subcategory from yours select contain houses. \\n Please remove houses first!'); window.history.go(-1); </script>\n";
        exit ;
      }        
    } 

    foreach ($cid as $catid) {
        removeCategoriesFromDB($catid) ;
    } 

    $msg = (count($err) > 1 ? "Categories " : _CATEGORIES_NAME . " ") . _DELETED;
    mosRedirect('index.php?option=com_realestatemanager&section=categories&mosmsg=' . $msg) ;
} 




/**
* Publishes or Unpublishes one or more categories
* 
* @param string $ The name of the category section
* @param integer $ A unique category id (passed from an edit form)
* @param array $ An array of unique category id numbers
* @param integer $ 0 if unpublishing, 1 if publishing
* @param string $ The name of the current user
*/

function publishCategories($section, $categoryid = null, $cid = null, $publish = 1)
{
    global $database, $my;

    if (!is_array($cid)) {
        $cid = array();
    } 
    if ($categoryid) {
        $cid[] = $categoryid;
    } 

    if (count($cid) < 1) {
        $action = $publish ? _PUBLISH : _DML_UNPUBLISH;
        echo "<script> alert('" . _DML_SELECTCATTO . " $action'); window.history.go(-1);</script>\n";
        exit;
    } 

    $cids = implode(',', $cid);

    $query = "UPDATE #__rem_main_categories SET published='$publish'"
     . "\nWHERE id IN ($cids) AND (checked_out=0 OR (checked_out='$my->id'))" ;
    $database->setQuery($query);
    if (!$database->query()) {
        echo "<script> alert('" . $database->getErrorMsg() . "'); window.history.go(-1); </script>\n";
        exit();
    } 

    if (count($cid) == 1) {
        $row = new mainRealEstateCategories($database);
        $row->checkin($cid[0]);
    } 

    mosRedirect('index.php?option=com_realestatemanager&section=categories');
} 

/**
* Cancels an edit operation
* 
* @param string $ The name of the category section
* @param integer $ A unique category id
*/
function cancelCategory()
{
    global $database;

    $row = new mainRealEstateCategories($database);
    $row->bind($_POST);
    $row->checkin();
    mosRedirect('index.php?option=com_realestatemanager&section=categories');
} 

/**
* Moves the order of a record
* 
* @param integer $ The increment to reorder by
*/
function orderCategory($uid, $inc)
{
    global $database;
    $row = new mainRealEstateCategories($database);
    $row->load($uid);
	if($row->ordering == 1 && $inc == -1) mosRedirect('index.php?option=com_realestatemanager&section=categories');

    $new_order = $row->ordering + $inc ;
	
    //change ordering - for other element
    $query = "UPDATE #__rem_main_categories SET ordering='".($row->ordering)."'"
     . "\nWHERE parent_id = $row->parent_id and ordering=$new_order" ;
    $database->setQuery($query);
	$database->query();

    //change ordering - for this element
    $query = "UPDATE #__rem_main_categories SET ordering='".$new_order."'"
     . "\nWHERE id = $uid" ;
    $database->setQuery($query);
	$database->query();

    mosRedirect('index.php?option=com_realestatemanager&section=categories');

} 

/**
* changes the access level of a record
* 
* @param integer $ The increment to reorder by
*/
function accessCategory($uid, $access)
{
    global $database;

    $row = new mainRealEstateCategories($database);
    $row->load($uid);
    $row->access = $access;

    if (!$row->check()) {
        return $row->getError();
    } 
    if (!$row->store()) {
        return $row->getError();
    } 

    mosRedirect('index.php?option=com_realestatemanager&section=categories');
} 








function update_review($title,$comment,$rating,$review_id ) {
	global $database;

  $review = new mosRealEstateManager_review($database);
  $review->load($review_id);
  

  if (!$review->bind($_POST)) {
    echo "<script> alert('".$review->getError()."'); window.history.go(-1); </script>\n";
    exit ();
  }
  
  if (!$review->check()) {
    echo "<script> alert('".$review->getError()."'); window.history.go(-1); </script>\n";
    exit ();
  }
  
  if (!$review->store()) {
    echo "<script> alert('".$review->getError()."'); window.history.go(-1); </script>\n";
    exit ();
  }
    
    
/*	//update review where id =.. ;
	$database->setQuery('update #__rem_review set rating='.$rating.
		', title="'.$title.'", comment="'.$comment.'" where id = '.$review_id.' ;' );
			
	$database->query();
	echo $database->getErrorMsg();
*/
}


function edit_review($option, $review_id,$house_id) {
	global $database;


	$database->setQuery("SELECT * FROM #__rem_review WHERE id=".$review_id." ");

	$review = $database->loadObjectList();

	echo $database->getErrorMsg();


	HTML_realestatemanager :: edit_review($option, $house_id, $review);

}

/*
* Function for delete coment
* (comment for every house) 
* in database.
*/

function delete_review($option, $id) {
	global $database;

	//delete review where id =.. ;
	$database->setQuery("DELETE FROM #__rem_review WHERE #__rem_review.id=".$id.";");
			
	$database->query();
	echo $database->getErrorMsg();
}

function showInfo($option, $bid){

	if(is_array($bid) && count($bid) > 0){
		$bid = $bid[0];
	}

	echo "Test: " . $bid;
}



function decline_rent_requests($option, $bids){

	global $database,$realestatemanager_configuration;
    $datas = array();

	foreach($bids as $bid){
		$rent_request = new mosRealEstateManager_rent_request($database);
		$rent_request->load($bid);
		$tmp = $rent_request->decline();

		if($tmp != null){
			echo "<script> alert('" .$tmp . "'); window.history.go(-1); </script>\n";
			exit ();
		}
	}

	mosRedirect("index.php?option=$option&task=rent_requests");
}

function accept_rent_requests($option, $bids){

	global $database,$realestatemanager_configuration;
    $datas = array();

	foreach($bids as $bid){
		$rent_request = new mosRealEstateManager_rent_request($database);
		
		$rent_request->load($bid);

		$tmp = $rent_request->accept();
		
		if($tmp != null){
			echo "<script> alert('" .$tmp . "'); window.history.go(-1); </script>\n";
			exit ();
		}
  }
 mosRedirect("index.php?option=$option&task=rent_requests");
}


function accept_buying_requests($option, $bids){
    global $database;
    foreach ($bids as $bid) {
        $buying_request = new mosRealEstateManager_buying_request($database);
        $buying_request->load($bid);

        $buying_request->delete($bid);
        if ($tmp != null) {
            echo "<script> alert('" . $tmp . "'); window.history.go(-1); </script>\n";
            exit ();
        }

    }
    
    mosRedirect("index.php?option=$option&task=buying_requests");
}


function decline_buying_requests($option, $bids) {
    global $database;

    foreach ($bids as $bid) {
        $buying_request = new mosRealEstateManager_buying_request($database);
        $buying_request->load($bid);
        $tmp = $buying_request->decline();
        if ($tmp != null) {
            echo "<script> alert('" . $tmp . "'); window.history.go(-1); </script>\n";
            exit ();
        }
    }

    mosRedirect("index.php?option=$option&task=buying_requests");
}


//*********   begin add for button print in Manager houses   ***********
function print_houses($option) {

	global $mosConfig_live_site, $database, $mainframe, $mosConfig_list_limit;

  if(!array_key_exists('bid', $_POST) )
  {
      echo "<script> alert('Please select some house'); window.history.go(-1); </script>\n";
      exit;  
  }  
  else 
  {
    $bid = $_POST['bid']; 
    $bids = implode(',',$bid);
  }
  
  //*************   begin for houses request   **************************
  $limit = $mainframe->getUserStateFromRequest("viewlistlimit", 'limit', $mosConfig_list_limit);
  $limitstart = $mainframe->getUserStateFromRequest("view{$option}limitstart", 'limitstart', 0);
  $catid = $mainframe->getUserStateFromRequest("catid{$option}", 'catid', 0);
  $rent = $mainframe->getUserStateFromRequest("rent{$option}", 'rent', 0);
  $pub = $mainframe->getUserStateFromRequest("pub{$option}", 'pub', 0);



  $search = $mainframe->getUserStateFromRequest("search{$option}", 'search', '');
  $search = $database->getEscaped(trim(strtolower($search)));

  $where = array ();

  if ($rent == "rent") {
    array_push($where, "a.fk_rentid <> 0");
  } else if ($rent == "not_rent") {
    array_push($where, "a.fk_rentid = 0");
  }

  if ($pub == "pub") {
    array_push($where, "a.published = 1");
  } else if ($pub == "not_pub") {
    array_push($where, "a.published = 0");
  }

  if ($catid > 0) {
    array_push($where, "a.catid='$catid'");
  }


  $database->setQuery("SELECT count(*) FROM #__rem_houses AS a".
            "\nLEFT JOIN #__rem_rent AS l".
            "\nON a.fk_rentid = l.id". 
            (count($where) ? "\nWHERE ".implode(' AND ', $where) : ""));
  $total = $database->loadResult();
  echo $database->getErrorMsg();

  $pageNav = new JPagination( $total, $limitstart, $limit ); // for J 1.6

  $selectstring = "SELECT a.*, GROUP_CONCAT(cc.title SEPARATOR ', ') AS category, 
               l.id as rentid, l.rent_from as rent_from, l.rent_return as 
               rent_return,            
               l.rent_until as rent_until, u.name AS editor,  
               l.user_name as user_name, l.user_email as user_email, l.user_mailing as user_mailing
               FROM #__rem_houses AS a
               LEFT JOIN #__rem_categories AS hc ON hc.iditem = a.id 
               LEFT JOIN #__rem_main_categories AS cc ON cc.id = hc.idcat  
               LEFT JOIN #__rem_rent AS l ON a.fk_rentid = l.id
               LEFT JOIN #__users AS u ON u.id = a.checked_out                 
               WHERE a.id IN ($bids) 
               GROUP BY a.id" ;

  $database->setQuery($selectstring);
  $rows = $database->loadObjectList();

  if ($database->getErrorNum()) {
    echo $database->stderr();
    return false;
  }
  
//**********************   end for houses request   *****************************

	HTML_realestatemanager :: showPrintHouses($rows);

}//end print_houses()


function print_item($option) {

	$rows = $_SESSION['rows'];
	HTML_realestatemanager :: showPrintItem($rows);

}
//*********************   end add for button print in Manager houses   *************


function rent_requests($option, $bid){

	global $database, $mainframe, $mosConfig_list_limit;
  $mainframe = JFactory::getApplication();

	$limit = $mainframe->getUserStateFromRequest("viewlistlimit", 'limit', $mosConfig_list_limit);
	$limitstart = $mainframe->getUserStateFromRequest("view{$option}limitstart", 'limitstart', 0);

	$database->setQuery("SELECT count(*) FROM #__rem_houses AS a".
						"\nLEFT JOIN #__rem_rent_request AS l".
						"\nON l.fk_houseid = a.id". 
						"\nWHERE l.status = 0");
	$total = $database->loadResult();
	echo $database->getErrorMsg();

	$pageNav = new JPagination( $total, $limitstart, $limit ); // for J 1.6

	$database->setQuery("SELECT * FROM #__rem_houses AS a".
						"\nLEFT JOIN #__rem_rent_request AS l".
						"\nON l.fk_houseid = a.id". 
						"\nWHERE l.status = 0".
						"\nORDER BY l.rent_from, l.rent_until, l.user_name".
						"\nLIMIT $pageNav->limitstart,$pageNav->limit;");
	$rent_requests = $database->loadObjectList();
	echo $database->getErrorMsg();

	//	print_r($total);	

	HTML_realestatemanager :: showRequestRentHouses($option, $rent_requests, $pageNav);
}

function buying_requests($option){
	
	global $database, $mainframe, $mosConfig_list_limit;
  $mainframe = JFactory::getApplication();

	$limit = $mainframe->getUserStateFromRequest("viewlistlimit", 'limit', $mosConfig_list_limit);
	$limitstart = $mainframe->getUserStateFromRequest("view{$option}limitstart", 'limitstart', 0);

	$database->setQuery("SELECT count(*) FROM #__rem_houses AS a".
						"\nLEFT JOIN #__rem_buying_request AS s".
						"\nON s.fk_houseid = a.id". 
						"\nWHERE s.status = 0");
	$total = $database->loadResult();
	echo $database->getErrorMsg();

  $pageNav = new JPagination( $total, $limitstart, $limit ); // for J 1.6

	$database->setQuery("SELECT * FROM #__rem_houses AS a".
						"\nLEFT JOIN #__rem_buying_request AS s".
						"\nON s.fk_houseid = a.id". 
						"\nWHERE s.status = 0".
						"\nORDER BY s.customer_name".
						"\nLIMIT $pageNav->limitstart,$pageNav->limit;");
	$rent_requests = $database->loadObjectList();
	echo $database->getErrorMsg();
	HTML_realestatemanager ::showRequestBuyingHouses($option, $rent_requests, $pageNav);
}


/**
* Compiles a list of records
* @param database - A database connector object
* select categories
*/
function showHouses($option)
{
  global $database, $mainframe, $mosConfig_list_limit;
  $mainframe = JFactory::getApplication();

	$limit = $mainframe->getUserStateFromRequest("viewlistlimit", 'limit', $mosConfig_list_limit);
	$limitstart = $mainframe->getUserStateFromRequest("view{$option}limitstart", 'limitstart', 0);
	$catid = $mainframe->getUserStateFromRequest("catid{$option}", 'catid', '-1');//old 0
	$rent = $mainframe->getUserStateFromRequest("rent{$option}", 'rent', '-1');//add nik
	$pub = $mainframe->getUserStateFromRequest("pub{$option}", 'pub', '-1');//add nik

	$search = $mainframe->getUserStateFromRequest("search{$option}", 'search', '');
	$search = $database->getEscaped(trim(strtolower($search)));

	$where = array ();

	if ($rent == "rent") {
		array_push($where, "a.fk_rentid <> 0");
	} else if ($rent == "not_rent") {
		array_push($where, "a.fk_rentid = 0");
	} 
	if ($pub== "pub") {
		array_push($where, "a.published = 1");
	} else if ($pub == "not_pub") {
		array_push($where, "a.published = 0");
	}
	if ($catid > 0) {
    array_push($where, "hc.idcat='$catid'");
	}
	

	if ($search) {
		array_push($where, "(LOWER(a.htitle) LIKE '%$search%' OR LOWER(a.hlocation) LIKE '%$search%' OR LOWER(a.houseid) LIKE '%$search%')");
	}


	$database->setQuery("SELECT count(*) FROM #__rem_houses AS a".
            "\nLEFT JOIN #__rem_categories AS hc ON a.id=hc.iditem" .
						"\nLEFT JOIN #__rem_rent AS l".
						"\nON a.fk_rentid = l.id". 
						(count($where) ? "\nWHERE ".implode(' AND ', $where) : ""));

	$total = $database->loadResult();
	echo $database->getErrorMsg();

  $pageNav = new JPagination( $total, $limitstart, $limit );

  $selectstring = "SELECT a.*, GROUP_CONCAT(cc.title SEPARATOR ', ') AS category, 
            l.id as rentid, l.rent_from as rent_from, l.rent_return as rent_return,
            l.rent_until as rent_until, u.name AS editor" .
            "\nFROM #__rem_houses AS a" .
            "\nLEFT JOIN #__rem_categories AS hc ON hc.iditem = a.id" .
            "\nLEFT JOIN #__rem_main_categories AS cc ON cc.id = hc.idcat" .
            "\nLEFT JOIN #__rem_rent AS l ON l.fk_houseid = a.id  and l.rent_return is null " .
            "\nLEFT JOIN #__users AS u ON u.id = a.checked_out" .
            (count($where) ? "\nWHERE " . implode(' AND ', $where) : "") .
            "\nGROUP BY a.id" .
            "\nORDER BY a.htitle " .
            "\nLIMIT $pageNav->limitstart,$pageNav->limit;";
  
	$database->setQuery($selectstring);
	$rows = $database->loadObjectList();

	//echo $rows[0];exit;	

	if ($database->getErrorNum()) {
		echo $database->stderr();
		return false;
	}

	// get list of categories
	/*
	 * select list treeSelectList
	 */

	$categories[] = mosHTML :: makeOption('0', _REALESTATE_MANAGER_LABEL_SELECT_CATEGORIES);
	$categories[] = mosHTML :: makeOption('-1', _REALESTATE_MANAGER_LABEL_SELECT_ALL_CATEGORIES);
	//$database->setQuery("SELECT id AS value, title AS text FROM #__categories"."\nWHERE section='com_realestatemanager' ORDER BY ordering");
//	$categories = array_merge($categories, $database->loadObjectList());//old valid
//	$clist = mosHTML :: selectList($categories, 'catid', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $catid);//old valid

//*************   begin add for sub category in select in manager houses   *************
	$options = $categories;
	$id = 0;//$categories_array;
        $list = CAT_Utils::categoryArray();

        $cat = new mainRealEstateCategories($database);
        $cat->load($id);

        $this_treename = '';
        foreach ($list as $item) {
            if ($this_treename) {
                if ($item->id != $cat->id && strpos($item->treename, $this_treename) === false) {
                    $options[] = mosHTML::makeOption($item->id, $item->treename);
                }
            } else {
                if ($item->id != $cat->id) {
                    $options[] = mosHTML::makeOption($item->id, $item->treename);
                } else {
                    $this_treename = "$item->treename/";
                }
            }
        }

	$clist = mosHTML::selectList($options, 'catid', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $catid);//new nik edit

//	$clist = mosHTML :: selectList($categories, 'catid', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $catid);//old valid
//*****  end add for sub category in select in manager houses   **********

	$rentmenu[] = mosHTML :: makeOption('0', _REALESTATE_MANAGER_LABEL_SELECT_TO_RENT);
	$rentmenu[] = mosHTML :: makeOption('-1', _REALESTATE_MANAGER_LABEL_SELECT_ALL_RENT);
	$rentmenu[] = mosHTML :: makeOption('not_rent', _REALESTATE_MANAGER_LABEL_SELECT_NOT_RENT);
	$rentmenu[] = mosHTML :: makeOption('rent', _REALESTATE_MANAGER_LABEL_SELECT_RENT);

	$rentlist = mosHTML :: selectList($rentmenu, 'rent', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $rent);

	$pubmenu[] = mosHTML :: makeOption('0', _REALESTATE_MANAGER_LABEL_SELECT_TO_PUBLIC);
	$pubmenu[] = mosHTML :: makeOption('-1', _REALESTATE_MANAGER_LABEL_SELECT_ALL_PUBLIC);
	$pubmenu[] = mosHTML :: makeOption('not_pub', _REALESTATE_MANAGER_LABEL_SELECT_NOT_PUBLIC);
	$pubmenu[] = mosHTML :: makeOption('pub', _REALESTATE_MANAGER_LABEL_SELECT_PUBLIC);

	$publist = mosHTML :: selectList($pubmenu, 'pub', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $pub);
	

	HTML_realestatemanager :: showHouses($option, $rows, $clist, $rentlist, $publist, $search, $pageNav);
}


/**
* Compiles information to add or edit houses
* @param integer bid The unique id of the record to edit (0 if new)
* @param array option the current options
*/



function editHouse($option,$bid)
{
	global $database, $my, $mosConfig_live_site, $realestatemanager_configuration;

	$house = new mosRealEstateManager($database);
	//print_r($house);
	// load the row from the db table
	$house->load(intval($bid));
  // get list of categories
    $categories=array();
    $categories[] = mosHTML :: makeOption('0', _REALESTATE_MANAGER_LABEL_SELECT_CATEGORIES);

    $query = "SELECT  id ,name, parent_id as parent"
            . "\n FROM #__rem_main_categories"
            . "\n WHERE section='com_realestatemanager'"
            . "\n AND published > 0"
            . "\n ORDER BY parent_id, ordering";

    $database->setQuery($query);
    $rows = $database->loadObjectList();


    // establish the hierarchy of the categories
    $children = array();
    // first pass - collect children
    foreach ($rows as $v) {
        $pt = $v->parent;
        $list = @$children[$pt] ? $children[$pt] : array();
        array_push($list, $v);
        $children[$pt] = $list;
    }

    // second pass - get an indent list of the items
    $list = houseLibraryTreeRecurse(0, '', array(), $children);

    //echo '<pre>';var_dump( $list);echo '</pre>';exit;
    foreach ($list as $i => $item) {
        $item->text = $item->treename;
        $item->value = $item->id;
        $list[$i] = $item;
    }
  
      $categories = array_merge($categories, $list);

    if (count($categories) <= 1) {
        mosRedirect("index.php?option=com_realestatemanager&section=categories",
                _REALESTATE_MANAGER_ADMIN_IMPEXP_ADD);
    }
    $house->setCatIds();
    $clist = mosHTML :: selectList($categories, 'catid[]', 'class="inputbox" multiple', 'value', 'text', $house->catid);

	//get Rating
	$retVal2 = mosRealEstateManagerOthers :: getRatingArray();
	$rating = null;
	for ($i = 0, $n = count($retVal2); $i < $n; $i ++) {
		$help = & $retVal2[$i];
		$rating[] = mosHTML :: makeOption($help[0], $help[1]);
	}

	/*$ratinglist = mosHTML :: selectList($rating, 'rating', 'class="inputbox" size="1"', 'value', 'text', $house->rating);*/

	//delete ehouse?
	$help = str_replace($mosConfig_live_site, "", $house->edok_link);
	$delete_ehouse_yesno[] = mosHTML :: makeOption($help, _REALESTATE_MANAGER_YES);
	$delete_ehouse_yesno[] = mosHTML :: makeOption('0', _REALESTATE_MANAGER_NO);
	$delete_edoc = mosHTML :: RadioList($delete_ehouse_yesno, 'delete_edoc',
     'class="inputbox"', '0', 'value', 'text');

	// fail if checked out not by 'me'
	if ($house->checked_out && $house->checked_out <> $my->id) {
		mosRedirect("index.php?option=$option", _REALESTATE_MANAGER_IS_EDITED);
	}

	if ($bid) {
		$house->checkout($my->id);
	} else {
		// initialise new record
		$house->published = 0;
		$house->approved = 0;
	}

//print_r($house);exit;

//*****************************   begin for reviews **************************//
	$database->setQuery("select a.* from #__rem_review a ".
						" WHERE a.fk_houseid=".$bid." ORDER BY date ;");
	$reviews = $database->loadObjectList();
//echo "reviews::"; print_r($reviews);
//**********************   end for reviews   *****************************//

	//cоздание списка "тип сделки"
  	$listing_type[] = mosHtml::makeOption('0',_REALESTATE_MANAGER_ADMIN_PLEASE_SEL);
	$listing_type[] = mosHtml::makeOption('foreclosure',_REALESTATE_MANAGER_OPTION_FORECLOSURE);
	$listing_type[] = mosHtml::makeOption('house for rent',_REALESTATE_MANAGER_OPTION_HOUSE_FOR_RENT);
	$listing_type[] = mosHtml::makeOption('room for rent',_REALESTATE_MANAGER_OPTION_ROOM_FOR_RENT);
	$listing_type[] = mosHtml::makeOption('for sale',_REALESTATE_MANAGER_OPTION_FOR_SALE);
	$listing_type[] = mosHtml::makeOption('new home',_REALESTATE_MANAGER_OPTION_NEW_HOME);
	$listing_type[] = mosHtml::makeOption('sublet',_REALESTATE_MANAGER_OPTION_SUBLET);
	$listing_type_list = mosHTML :: selectList($listing_type, 'listing_type', 'class="inputbox" size="1"', 'value', 'text', $house->listing_type);

	//cоздание списка "тип цены"
  $test[] = mosHtml::makeOption('0',_REALESTATE_MANAGER_ADMIN_PLEASE_SEL);
	$test[] = mosHtml::makeOption('negotiable',_REALESTATE_MANAGER_OPTION_NEGOTIABLE);
	$test[] = mosHtml::makeOption('starting',_REALESTATE_MANAGER_OPTION_STARTING);
	$test_list = mosHTML :: selectList($test, 'price_type', 'class="inputbox" size="1"', 'value', 'text', $house->price_type);

	//cоздание списка "статус сделки"
  $listing_status_type[] = mosHtml::makeOption('0',_REALESTATE_MANAGER_ADMIN_PLEASE_SEL);
	$listing_status_type[] = mosHtml::makeOption('active',_REALESTATE_MANAGER_OPTION_ACTIVE);
	$listing_status_type[] = mosHtml::makeOption('offer',_REALESTATE_MANAGER_OPTION_OFFER);
	$listing_status_type[] = mosHtml::makeOption('contract',_REALESTATE_MANAGER_OPTION_CONTRACT);
	$listing_status_type[] = mosHtml::makeOption('closed',_REALESTATE_MANAGER_OPTION_CLOSED);
	$listing_status_type[] = mosHtml::makeOption('withdrawn',_REALESTATE_MANAGER_OPTION_WITHDRAWN);
	$listing_status_list = mosHTML :: selectList($listing_status_type, 'listing_status', 'class="inputbox" size="1"', 'value', 'text', $house->listing_status);

	





	$property_type[] = mosHtml::makeOption('0',_REALESTATE_MANAGER_ADMIN_PLEASE_SEL);
    $property_type[] = mosHtml::makeOption("townhouse",_REALESTATE_MANAGER_OPTION_TOWNHOUSE);
	$property_type[] = mosHtml::makeOption("apartment",_REALESTATE_MANAGER_OPTION_APARTMENT);
	$property_type[] = mosHtml::makeOption("warehouse",_REALESTATE_MANAGER_OPTION_WAREHOUSE);
	$property_type[] = mosHtml::makeOption("office",_REALESTATE_MANAGER_OPTION_OFFICE);
	$property_type[] = mosHtml::makeOption("garage",_REALESTATE_MANAGER_OPTION_GARAGE);
	$property_type[] = mosHtml::makeOption("store",_REALESTATE_MANAGER_OPTION_STORE);
	$property_type[] = mosHtml::makeOption("houseband", _REALESTATE_MANAGER_OPTION_HAOUSE_BAND);
	$property_type[] = mosHtml::makeOption("housegav", _REALESTATE_MANAGER_OPTION_HOUSE_GAV);
	$property_type[] = mosHtml::makeOption("housegem",_REALESTATE_MANAGER_OPTION_HOUSE_GEM);
	$property_type[] = mosHtml::makeOption("houseind",_REALESTATE_MANAGER_OPTION_IND_HOUSE);
	$property_type[] = mosHtml::makeOption("parking",_REALESTATE_MANAGER_OPTION_PARKING);
	$property_type[] = mosHtml::makeOption("pavillion",_REALESTATE_MANAGER_OPTION_PAVILLION);
	$property_type[] = mosHtml::makeOption("building",_REALESTATE_MANAGER_OPTION_BUILDING);
	$property_type[] = mosHtml::makeOption("farm",_REALESTATE_MANAGER_OPTION_FARM);
	$property_type[] = mosHtml::makeOption("smallfarm",_REALESTATE_MANAGER_OPTION_SMALLFARM);
	$property_type[] = mosHtml::makeOption("rest",_REALESTATE_MANAGER_OPTION_REST);
	$property_type[] = mosHtml::makeOption("land",_REALESTATE_MANAGER_OPTION_LAND);
	$property_type_list = mosHTML :: selectList($property_type, 'property_type', 'class="inputbox" size="1"', 'value', 'text', $house->property_type);
	
	// <-- SOFIA
	$typology[] = mosHtml::makeOption('0',_REALESTATE_MANAGER_ADMIN_PLEASE_SEL);
	$typology[] = mosHtml::makeOption("t0", "T0");
	$typology[] = mosHtml::makeOption("t0+1", "T0+1");
	$typology[] = mosHtml::makeOption("t1", "T1");
	$typology[] = mosHtml::makeOption("t1+1", "T1+1");
	$typology[] = mosHtml::makeOption("t2", "T2");
	$typology[] = mosHtml::makeOption("t2+1", "T2+1");
	$typology[] = mosHtml::makeOption("t3", "T3");
	$typology[] = mosHtml::makeOption("t3+1", "T3+1");
	$typology[] = mosHtml::makeOption("t4", "T4");
	$typology[] = mosHtml::makeOption("t4+1", "T4+1");
	$typology[] = mosHtml::makeOption(">=t5", ">=T5");
	$typology[] = mosHtml::makeOption("sem", "Outros");
	$typology_list = mosHTML :: selectList($typology, 'typology', 'class="inputbox" size="1"', 'value', 'text', $house->typology);
	// -->
	
	// <-- DISTRITOS
	$query = "SELECT id, designacao FROM   #__districts ";
	$database->setQuery($query);
	$temp = $database->loadObjectList();
	$districts = array();
	$districts[] = mosHtml::makeOption('0',_REALESTATE_MANAGER_ADMIN_PLEASE_SEL);
	foreach($temp as $value){
		$districts[] = mosHtml::makeOption($value->id, $value->designacao);
	}
	$districts = mosHTML :: selectList($districts, 'district', 'class="inputbox" size="1"', 'value', 'text', $house->district);
  	// -->

	// <-- CONCELHOS
	$councils = array();
	$councils[] = mosHtml::makeOption('0',_REALESTATE_MANAGER_ADMIN_PLEASE_SEL);
	if(isset($house->district)){
		$query = "SELECT id, designacao FROM   #__councils WHERE distrito_id = ".$house->district." ";
		$database->setQuery($query);
		$temp = $database->loadObjectList();
		foreach($temp as $value){
			$councils[] = mosHtml::makeOption($value->id, $value->designacao);
		}
	}
	$councils = mosHTML :: selectList($councils, 'council', 'class="inputbox" size="1"', 'value', 'text', $house->council);
  	// -->

	// <-- FREGUESIAS
	$parish = array();
	$parish[] = mosHtml::makeOption('0',_REALESTATE_MANAGER_ADMIN_PLEASE_SEL);
	if(isset($house->council)){
		$query = "SELECT id, designacao FROM   #__parish WHERE concelho_id = ".$house->council." ";
		$database->setQuery($query);
		$temp = $database->loadObjectList();
		foreach($temp as $value){
			$parish[] = mosHtml::makeOption($value->id, $value->designacao);
		}
	}
	$parish = mosHTML :: selectList($parish, 'parish', 'class="inputbox" size="1"', 'value', 'text', $house->parish);
  	// -->
	
	//cоздание списка "класс провайдера"
	$provider_class[] = mosHtml::makeOption('0',_REALESTATE_MANAGER_ADMIN_PLEASE_SEL);
	$provider_class[] = mosHtml::makeOption('agent',_REALESTATE_MANAGER_OPTION_AGENT);
//	$provider_class[] = mosHtml::makeOption('aggregator',_REALESTATE_MANAGER_OPTION_AGGREGATOR);
	$provider_class[] = mosHtml::makeOption('broker',_REALESTATE_MANAGER_OPTION_BROKER);
	$provider_class[] = mosHtml::makeOption('franchisor',_REALESTATE_MANAGER_OPTION_FRANCHISOR);
	$provider_class[] = mosHtml::makeOption('homebuilder',_REALESTATE_MANAGER_OPTION_HOMEBUILDER);
//	$provider_class[] = mosHtml::makeOption('publisher',_REALESTATE_MANAGER_OPTION_PUBLISHER);
//	$provider_class[] = mosHtml::makeOption('mls',"mls");
	$provider_class_list = mosHTML :: selectList($provider_class, 'provider_class', 'class="inputbox" size="1"', 'value', 'text', $house->provider_class);

	//cоздание списка "районирование"
  $zoning[] = mosHtml::makeOption('0',_REALESTATE_MANAGER_ADMIN_PLEASE_SEL);
	$zoning[] = mosHtml::makeOption('agricultural',_REALESTATE_MANAGER_OPTION_AGRICULTURAL);
	$zoning[] = mosHtml::makeOption('commercial',_REALESTATE_MANAGER_OPTION_COMMERCIAL);
	$zoning[] = mosHtml::makeOption('industrial',_REALESTATE_MANAGER_OPTION_INDUSTRIAL);
	$zoning[] = mosHtml::makeOption('recreational',_REALESTATE_MANAGER_OPTION_RECREATIONAL);
	$zoning[] = mosHtml::makeOption('residential',_REALESTATE_MANAGER_OPTION_RESIDENTIAL);
	$zoning[] = mosHtml::makeOption('unincorporated',_REALESTATE_MANAGER_OPTION_UNINCORPORATED);
	$zoning_list = mosHTML :: selectList($zoning, 'zoning', 'class="inputbox" size="1"', 'value', 'text', $house->zoning);

	//cоздание списка "style"
  $style[] = mosHtml::makeOption('0',_REALESTATE_MANAGER_ADMIN_PLEASE_SEL);
	$style[] = mosHtml::makeOption('Cape Cod',_REALESTATE_MANAGER_OPTION_CAPE_COD);
	$style[] = mosHtml::makeOption('Colonial',_REALESTATE_MANAGER_OPTION_COLONIAL);
	$style[] = mosHtml::makeOption('Craftsman',_REALESTATE_MANAGER_OPTION_CRAFTSMAN);
	$style[] = mosHtml::makeOption('Gothic',_REALESTATE_MANAGER_OPTION_GOTHIC);
	$style[] = mosHtml::makeOption('Prairie',_REALESTATE_MANAGER_OPTION_PRAIRIE);
	$style[] = mosHtml::makeOption('Ranch',_REALESTATE_MANAGER_OPTION_RANCH2);
	$style[] = mosHtml::makeOption('Split Level',_REALESTATE_MANAGER_OPTION_SPLIT_LEVEL);
	$style[] = mosHtml::makeOption('Tudor',_REALESTATE_MANAGER_OPTION_TUDOR);
	$style[] = mosHtml::makeOption('Victorian Queen Anne',_REALESTATE_MANAGER_OPTION_VICTORIAN_QUEEN_ANNE);
	$style_list = mosHTML :: selectList($style, 'style', 'class="inputbox" size="1"', 'value', 'text', $house->style);
	
	$query = "select main_img from #__rem_photos WHERE fk_houseid=$house->id order by id";
	$database->setQuery( $query );
	$house_photos = $database->loadObjectList();


	HTML_realestatemanager :: editHouse($option, $house, $clist, $ratinglist, $delete_edoc, $reviews, $test_list, 
    $listing_status_list, $property_type_list, $typology_list, $districts, $councils, $parish, $listing_type_list, $provider_class_list, $zoning_list, 
    $style_list, $house_photos);
//print_r($test1);exit;
}


//***************Globally/Universally Unique Identifier****************************
function guid(){
    if (function_exists('com_create_guid')){
        return com_create_guid();
    }else{
        mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $hyphen = chr(45);// "-"
        $uuid = //chr(123)// "{"
                substr($charid, 0, 8).$hyphen
                .substr($charid, 8, 4).$hyphen
                .substr($charid,12, 4).$hyphen
                .substr($charid,16, 4).$hyphen
                .substr($charid,20,12);
                //.chr(125);// "}"
        return $uuid;
    }
}


/**
* Saves the record on an edit form submit
* @param database A database connector object
*/
function picture_thumbnail($file,$gallery=false){
  global $mosConfig_absolute_path, $realestatemanager_configuration;
  
  //разделение имени файла на имя и расширение
	$file_path=pathinfo($file);
	$file_type='.'.$file_path['extension'];
	$file_name=basename($file,$file_type);
/*  $file_name = substr($file, 0, strlen($file)-4);
  $file_type = substr($file, strlen($file)-4);*/
  if($gallery){
      $type="_gallery";
      $h_70 =220;
      $w_70 = 220;
  }
  else{
      $type="_mini";
      $h_70 = 70;
      $w_70 = 70;
  }
    
  // Setting the resize parameters
  list($width, $height) = getimagesize($mosConfig_absolute_path.'/components/com_realestatemanager/photos/'.$file);
  // Creating the Canvas
  $tn= imagecreatetruecolor($w_70, $h_70);
  
  //проверка типа
  switch (strtolower($file_type) ) {
      case '.png':
          echo 'type of your image is PNG';
	  $source = imagecreatefrompng($mosConfig_absolute_path.'/components/com_realestatemanager/photos/'.$file);
	  $file = imagecopyresized($tn, $source, 0, 0, 0, 0, $w_70, $h_70, $width, $height);
	  imagepng($tn,$mosConfig_absolute_path.'/components/com_realestatemanager/photos/'.$file_name.$type.$file_type);
	  break;
      case '.jpg':
          echo 'type of your image is JPG';
	  $source = imagecreatefromjpeg($mosConfig_absolute_path.'/components/com_realestatemanager/photos/'.$file);
	  $file = imagecopyresized($tn, $source, 0, 0, 0, 0, $w_70, $h_70, $width, $height);
	  imagejpeg($tn,$mosConfig_absolute_path.'/components/com_realestatemanager/photos/'.$file_name.$type.$file_type);
	  break;
		case '.jpeg':
          echo 'type of your image is JPEG';
	  $source = imagecreatefromjpeg($mosConfig_absolute_path.'/components/com_realestatemanager/photos/'.$file);
	  $file = imagecopyresized($tn, $source, 0, 0, 0, 0, $w_70, $h_70, $width, $height);
	  imagejpeg($tn,$mosConfig_absolute_path.'/components/com_realestatemanager/photos/'.$file_name.$type.$file_type);
	  break;
      case '.gif':
          echo 'type of your image is GIF';
	  $source = imagecreatefromgif($mosConfig_absolute_path.'/components/com_realestatemanager/photos/'.$file);
	  $file = imagecopyresized($tn, $source, 0, 0, 0, 0, $w_70, $h_70, $width, $height);
	  imagegif($tn,$mosConfig_absolute_path.'/components/com_realestatemanager/photos/'.$file_name.$type.$file_type);
	  break;
      default:
	  echo 'not support';
	  return;
  }
  return $file_name.$type.$file_type;
}


function saveHouse($option) 
{	
	global $database, $my,$mosConfig_absolute_path, $mosConfig_live_site, $realestatemanager_configuration;

	//check how the other info should be provided
	$house = new mosRealEstateManager($database);	
	$post = JRequest::get('post',JREQUEST_ALLOWHTML);
	
  if (!$house->bind($post)) {
    echo "<script> alert('".$house->getError()."'); window.history.go(-1); </script>\n";
    exit ();
  }

//if(isset($_POST[contacts]))
//{
$house->contacts=$_POST['contacts'];
//}
//print_r($_POST[houseid]);
//print_r($_POST);

//exit; 
	//сохранение основного изображения 
	$uploaddir = $mosConfig_absolute_path.'/components/com_realestatemanager/photos/';
	
   if($_FILES['image_link']['name']!= '') {
		$code=guid();
	$uploadfile = $uploaddir.$code."_".$_FILES['image_link']['name'];
	$file_name = $code."_".$_FILES['image_link']['name'];
	if(copy($_FILES['image_link']['tmp_name'], $uploadfile))
	{
	    $mini_file_name = picture_thumbnail($file_name);
      $gallery_file_name = picture_thumbnail($file_name,true);      
	    $house->image_link = $file_name; 

	    $idd=$_POST['houseid'];
	    $database->setQuery("UPDATE #__rem_houses SET image_link='$file_name' WHERE houseid=$idd");
				
			if (!$database->query()) {
  			echo "<script> alert('".$database->getErrorMsg()."');</script>\n";
			}
	}
   } //end if


  if($_POST['edok_link'] != '') $house->edok_link = $_POST['edok_link'];
  //delete ehouse file if neccesary
  $delete_edoc = mosGetParam($_POST, 'delete_edoc', 0);
  if($delete_edoc != '0'){

      $retVal = unlink($mosConfig_absolute_path . $delete_edoc);
      $house->edok_link = "";
  } 


	//storing e-house
	$edfile = $_FILES['edoc_file'];
	//check if fileupload is correct
	if($realestatemanager_configuration['edocs']['allow'] 
      && intval($edfile['error']) > 0 
      && intval($edfile['error']) < 4){

		echo "<script> alert('" . _REALESTATE_MANAGER_LABEL_EDOCUMENT_UPLOAD_ERROR . 
      "'); window.history.go(-1); </script>\n";
		exit ();

	} else if ($realestatemanager_configuration['edocs']['allow'] 
      && intval($edfile['error']) != 4){
	
		$uploaddir = $mosConfig_absolute_path . $realestatemanager_configuration['edocs']['location'];
		$file_new = $uploaddir.$_FILES['edoc_file']['name'];

		if(!copy($edfile['tmp_name'],  $file_new)){
			echo "<script> alert('error: not copy'); window.history.go(-1); </script>\n";
		   exit ();
    	} else {
			$house->edok_link = $mosConfig_live_site .
     		$realestatemanager_configuration['edocs']['location'] . $edfile['name'];
		}
			
	}

	if (is_string($house)) {
		echo "<script> alert('".$house."'); window.history.go(-1); </script>\n";
		exit ();
	}
    $house->published=0;
    $house->approved=0;
  
   $house->date = date("Y-m-d H:i:s");
	if (!$house->check()) {
		echo "<script> alert('".$house->getError()."'); window.history.go(-1); </script>\n";
		exit ();
	}


	if(get_magic_quotes_gpc()) {
	       $house->description = stripslashes($house->description);  
	}
	if($house->is_featured==1)
		$house->is_featured=1;
	else
		$house->is_featured=0;

	if($house->district == 0)
		$house->district=NULL;
	if($house->council == 0)
		$house->council=NULL;
	if($house->parish == 0)
		$house->parish=NULL;

	if (!$house->store()) {
		echo "<script> alert('".$house->getError()."'); window.history.go(-1); </script>\n";
		exit ();
	}

  $house->saveCatIds($house->catid);
    //var_dump($house);
	$house->checkin();
	//$house->updateOrder( "catid='$house->catid'" );

	//SAVE FILES TO FOLDER photos
	$uploaddir = $mosConfig_absolute_path.'/components/com_realestatemanager/photos/';
	if (array_key_exists("new_photo_file", $_FILES)) {
		for ($i = 0; $i <= count($_FILES['new_photo_file']['name']); $i++) {
			$code=guid();
	      $uploadfile = $uploaddir.$code."_".$_FILES['new_photo_file']['name'][$i];

	      if(copy($_FILES['new_photo_file']['tmp_name'][$i], $uploadfile))
			{		
				$file_name = $code."_".$_FILES['new_photo_file']['name'][$i];
				$mini_file_name = picture_thumbnail($file_name);
				//save files name in DB
				$database->setQuery("INSERT INTO #__rem_photos VALUES ( '','$house->id','$mini_file_name','$file_name')");
				if (!$database->query()) {
			  		echo "<script> alert('".$database->getErrorMsg()."');</script>\n";
			  		$mini_file_name = picture_thumbnail($file_name);
			 	}
		 	}
		}
  }  //end if
	
	//CHECK FILES - SETED FOR DEL
	if (array_key_exists("del_main_photo", $_POST)) {
		$del_main_photo = $_POST['del_main_photo'];
		if($del_main_photo!=''){
			 $house->image_link = '';
			  unlink($mosConfig_absolute_path.'/components/com_realestatemanager/photos/'.
          $del_main_photo);
			  //take files extension
			$del_main_pth=pathinfo($del_main_photo);
			$del_main_photo_type='.'.$del_main_pth['extension'];
			$del_main_photo_name=basename($del_main_photo,$del_main_photo_type);
				
			  /*$del_main_photo_name = substr($del_main_photo, 0, strlen($del_main_photo)-4);
			  $del_main_photo_type = substr($del_main_photo, strlen($del_main_photo)-4);*/
			  unlink($mosConfig_absolute_path.'/components/com_realestatemanager/photos/'.
          $del_main_photo_name."_mini".$del_main_photo_type);
        unlink($mosConfig_absolute_path.'/components/com_realestatemanager/photos/'.
          $del_main_photo_name."_gallery".$del_main_photo_type);
		  }		
		//Update DB
			$idd=$_POST['houseid'];
			$database->setQuery("UPDATE #__rem_houses SET image_link='' WHERE houseid=$idd");		
			if (!$database->query()) {
  			echo "<script> alert('".$database->getErrorMsg()."');</script>\n";
			}
  } //end if	
		
	

	if (count($_POST['del_photos'])!=0)
	{ 
	   for ($i = 0; $i < count($_POST['del_photos']); $i++)
	   {
		   //echo $_POST['del_photos'][$i];
		   $del_photo = $_POST['del_photos'][$i];
		   $database->setQuery("DELETE FROM #__rem_photos WHERE main_img='$del_photo'");
		   if ($database->query()) {
		   	unlink($mosConfig_absolute_path.'/components/com_realestatemanager/photos/'. $del_photo);
		     //разделение имени файла на имя и расширение
				$del_photo_pth=pathinfo($del_photo);
				$del_photo_type='.'.$del_photo_pth['extension'];
				$del_photo_name=basename($del_photo,$del_photo_type);
			  /*$del_photo_name = substr($del_photo, 0, strlen($del_photo)-4);
		     $del_photo_type = substr($del_photo, strlen($del_photo)-4);*/
				unlink($mosConfig_absolute_path.'/components/com_realestatemanager/photos/'.
		     	$del_photo_name."_mini".$del_photo_type);
      	}   
     	}
   }
  
	$house->checkin();
	//$house->updateOrder( "catid='$house->catid'" );
	mosRedirect("index.php?option=$option");
}



/**
* Deletes one or more records
* @param array - An array of unique category id numbers
* @param string - The current author option
*/

function removeHouses($bid, $option) {
	
	global $database,$mosConfig_absolute_path ;

	if (!is_array($bid) || count($bid) < 1) {
		echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";
		exit;
	}

	if (count($bid)) { 	
		$bids = implode(',', $bid);
		


			//print_r($bids);exit;
		$database->setQuery("SELECT * FROM  #__rem_houses WHERE id IN (" . $bids . ")");
		
		$del_rent= $database->loadObjectList();
		   
		
		unlink($mosConfig_absolute_path.'/components/com_realestatemanager/photos/'.$del_rent[0]->image_link);
		$mini_pth=pathinfo($del_rent[0]->image_link);
		$miniEnd='.'.$mini_pth['extension'];
		$miniBeg=basename($del_rent[0]->image_link,$miniEnd);

		/*$miniBeg=substr($del_rent[0]->image_link,0,strpos($del_rent[0]->image_link,"."));
			
		$miniEnd=substr($del_rent[0]->image_link,-4);*/
//print_r('1111111111111111::'.$miniBeg.$miniEnd);exit;

	unlink($mosConfig_absolute_path.'/components/com_realestatemanager/photos/'.$miniBeg."_mini".$miniEnd);
  unlink($mosConfig_absolute_path.'/components/com_realestatemanager/photos/'.$miniBeg."_gallery".$miniEnd);

		$database->setQuery("DELETE FROM   #__rem_rent WHERE fk_houseid=".$del_rent[0]->houseid);
		if (!$database->query()) {
			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		}
		

		$database->setQuery("DELETE FROM #__rem_review WHERE fk_houseid IN ($bids)");
		if (!$database->query()) {
			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		}

		$database->setQuery("SELECT thumbnail_img, main_img FROM #__rem_photos WHERE fk_houseid IN ($bids)");
		$del_photos = $database->loadObjectList();
              for($i=0;$i<=count($del_photos);$i++){
		unlink($mosConfig_absolute_path.'/components/com_realestatemanager/photos/'.$del_photos[$i]->thumbnail_img);
		unlink($mosConfig_absolute_path.'/components/com_realestatemanager/photos/'.$del_photos[$i]->main_img);
			}
	
		//print_r($del_photos);exit;	
		
		$database->setQuery("DELETE FROM #__rem_photos WHERE fk_houseid IN ($bids)");
		if (!$database->query()) {
			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		}

    $database->setQuery("DELETE FROM #__rem_categories WHERE iditem IN ($bids)");
    if (!$database->query()) {
        echo "<script> alert('" . $database->getErrorMsg() . "'); window.history.go(-1); </script>\n";
    }
    
		$database->setQuery("DELETE FROM #__rem_houses WHERE id IN ($bids)");
		if (!$database->query()) {
			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		}
	}

	mosRedirect("index.php?option=$option");
}


/**
* Publishes or Unpublishes one or more records
* @param array - An array of unique category id numbers
* @param integer - 0 if unpublishing, 1 if publishing
* @param string - The current author option
*/
function publishHouses($bid, $publish, $option) {

	global $database, $my;

	$catid = mosGetParam($_POST, 'catid', array (0));

	if (!is_array($bid) || count($bid) < 1) {
		$action = $publish ? 'publish' : 'unpublish';
		echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
		exit;
	}

	$bids = implode(',', $bid);

	$database->setQuery("UPDATE #__rem_houses SET published='$publish'".
						"\nWHERE id IN ($bids) AND (checked_out=0 OR (checked_out='$my->id'))");
	if (!$database->query()) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit ();

	}

	if (count($bid) == 1) {
		$row = new mosRealEstateManager($database);
		$row->checkin($bid[0]);
	}

	mosRedirect("index.php?option=$option");
}


/**
 * Approve or Unapprove one or more records
 * @param array - An array of unique category id numbers
 * @param integer - 0 if unapprove, 1 if approve
 * @param string - The current author option
 */
function approveHouses($bid, $approve, $option) {

    global $database, $my;
    //echo $bid[0];exit;
    $catid = mosGetParam($_POST, 'catid', array(0));

    if (!is_array($bid) || count($bid) < 1) {
        $action = $approve ? 'approve' : 'unapprove';
        echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
        exit;
    }

    $bids = implode(',', $bid);

    $database->setQuery("UPDATE #__rem_houses SET published=$approve, approved='$approve'" .
            "\nWHERE id IN ($bids) AND (checked_out=0 OR (checked_out='$my->id'))");
    if (!$database->query()) {
        echo "<script> alert('" . $database->getErrorMsg() . "'); window.history.go(-1); </script>\n";
        exit ();
    }

    if (count($bid) == 1) {
        $row = new mosRealEstateManager($database);
        $row->checkin($bid[0]);
    }

    mosRedirect("index.php?option=$option");
}


/**
* Moves the order of a record
* @param integer - The increment to reorder by
*/

function orderHouses($bid, $inc, $option) {

	global $database;

	$house = new mosRealEstateManager($database);
	$house->load($bid);
	$house->move($inc);
	mosRedirect("index.php?option=$option");
}



/**
* Cancels an edit operation
* @param string - The current author option
*/
function cancelHouse($option) {

	global $database;
	$row = new mosRealEstateManager($database);
	$row->bind($_POST);
	$row->checkin();
	mosRedirect("index.php?option=$option");
}


function configure_save_frontend($option){
	global $my, $realestatemanager_configuration;
	
$str = '';
	$supArr = array();
	$supArr = mosGetParam($_POST, 'edocs_registrationlevel', 0);
	for($i = 0;$i<count($supArr);$i++)
		$str.=$supArr[$i].',';
	$str = substr($str,0,-1);
	$realestatemanager_configuration['edocs']['registrationlevel']=$str;
	
	$str = '';
	$supArr = mosGetParam($_POST, 'reviews_registrationlevel', 0);
	for($i = 0;$i<count($supArr);$i++)
		$str.=$supArr[$i].',';
	$str = substr($str,0,-1);
	$realestatemanager_configuration['reviews']['registrationlevel']=$str;
	
  $str = '';
	$supArr = mosGetParam($_POST, 'rentrequest_registrationlevel', 0);
	for($i = 0;$i<count($supArr);$i++)
		$str.=$supArr[$i].',';
	$str = substr($str,0,-1);
	$realestatemanager_configuration['rentrequest']['registrationlevel']=$str;
  
  $str = '';
	$supArr = mosGetParam($_POST, 'buyrequest_registrationlevel', 0);
	for($i = 0;$i<count($supArr);$i++)
		$str.=$supArr[$i].',';
	$str = substr($str,0,-1);
	$realestatemanager_configuration['buyrequest']['registrationlevel']=$str;
  $realestatemanager_configuration['reviews']['show']= mosGetParam($_POST, 'reviews_show', 0);

	$realestatemanager_configuration['rentstatus']['show']=mosGetParam($_POST, 'rentstatus_show', 0);

	$realestatemanager_configuration['buystatus']['show']=mosGetParam($_POST, 'buystatus_show', 0);

	$realestatemanager_configuration['edocs']['show']= mosGetParam($_POST, 'edocs_show', 0);

	$realestatemanager_configuration['price']['show']= mosGetParam($_POST, 'price_show', 0);
  //add for show in category picture
  $realestatemanager_configuration['cat_pic']['show'] = mosGetParam($_POST, 'cat_pic_show');
   
  $realestatemanager_configuration['page']['items'] = mosGetParam($_POST, 'page_items');
 //add for show subcategory 
  $realestatemanager_configuration['subcategory']['show'] = mosGetParam($_POST, 'subcategory_show');

  //google Map key
  $realestatemanager_configuration['google_map']['key'] = mosGetParam($_POST, 'google_map_key');

    //view type
    $realestatemanager_configuration['view_type'] = mosGetParam($_POST, 'view_type');
      
	mosRealEstateManagerOthers :: setParams();
	
}

function configure_save_backend($option){

	global $my, $realestatemanager_configuration;
 //$realestatemanager_configuration['tabs']['show']=mosGetParam($_POST, 'tabs_show', "");s
	$realestatemanager_configuration['edocs']['allow']= mosGetParam($_POST, 'edocs_allow', 0);
	$realestatemanager_configuration['edocs']['location']= mosGetParam($_POST, 'edocs_location',
    "/components/com_realestatemanager/edocs/");
	  $realestatemanager_configuration['update'] = mosGetParam($_POST, 'update',0);
//	$realestatemanager_configuration['edithouse']['check']['mls'] = mosGetParam($_POST, 'edithouse_check_mls', 0);

	mosRealEstateManagerOthers :: setParams();
}

function configure($option)
{

//configure_frontend
	global $my, $realestatemanager_configuration, $acl,$database;
  global $mosConfig_absolute_path;

  $group_children_tree = array ();
  
  include_once($mosConfig_absolute_path.'/administrator/components/com_users/models/groups.php'); // for J 1.6
  
  $model = &JModel::getInstance('Groups', 'UsersModel', array('ignore_request' => true));

  foreach ($g = $model->getItems() as $k => $v) { // $g contains basic usergroup items info
    $group_title = '.';
    for ($i=1; $i<=$g[$k]->level; $i++) 
    {
      $group_title .= '-';
    }
    $group_title .= '-'.$g[$k]->title;
    
    $group_children_tree[] = mosHTML :: makeOption($g[$k]->id, $group_title);
  }

	$yesno[] = mosHTML :: makeOption('1', _REALESTATE_MANAGER_YES);
	$yesno[] = mosHTML :: makeOption('0', _REALESTATE_MANAGER_NO);

	$gtree[] = mosHTML :: makeOption('-2', 'Everyone');
  $gtree = array_merge ( $gtree, $group_children_tree); // for J 1.6  

	$lists = array ();
  $f="";
  $s = explode(',',$realestatemanager_configuration['reviews']['registrationlevel']);
  for($i = 0;$i<count($s);$i++)
    $f[] = mosHTML::makeOption( $s[$i] );

	$lists['reviews']['show'] = mosHTML :: RadioList($yesno, 'reviews_show', 'class="inputbox"',
    $realestatemanager_configuration['reviews']['show'], 'value', 'text');
	$lists['reviews']['registrationlevel'] = mosHTML::selectList( $gtree, 'reviews_registrationlevel[]',
   'size="4" multiple="multiple"', 'value', 'text', $f);

  $f="";
  $s = explode(',',$realestatemanager_configuration['rentrequest']['registrationlevel']);
  for($i = 0;$i<count($s);$i++)
     $f[] = mosHTML::makeOption( $s[$i] );

	$lists['rentstatus']['show'] = mosHTML :: RadioList($yesno, 'rentstatus_show', 
    'class="inputbox"', $realestatemanager_configuration['rentstatus']['show'], 'value', 'text');

	$lists['rentrequest']['registrationlevel'] = mosHTML::selectList( $gtree, 
    'rentrequest_registrationlevel[]', 'size="4" multiple="multiple"', 'value', 'text', $f );

  $f="";
  $s = explode(',',$realestatemanager_configuration['buyrequest']['registrationlevel']);
  for($i = 0;$i<count($s);$i++)
     $f[] = mosHTML::makeOption( $s[$i] );

	$lists['buystatus']['show'] = mosHTML :: RadioList($yesno, 'buystatus_show', 
    'class="inputbox"', $realestatemanager_configuration['buystatus']['show'], 'value', 'text');

	$lists['buyrequest']['registrationlevel'] = mosHTML::selectList( $gtree, 
    'buyrequest_registrationlevel[]', 'size="4" multiple="multiple"', 'value', 'text', $f );

  $f="";
  $s = explode(',',$realestatemanager_configuration['edocs']['registrationlevel']);
  for($i = 0;$i<count($s);$i++)
      $f[] = mosHTML::makeOption( $s[$i] ); 

  $lists['edocs']['registrationlevel'] = mosHTML::selectList( $gtree, 'edocs_registrationlevel[]', 
    'size="4" multiple="multiple"', 'value', 'text', $f );  

	$lists['edocs']['show'] = mosHTML :: RadioList($yesno, 'edocs_show', 'class="inputbox"',
    $realestatemanager_configuration['edocs']['show'], 'value', 'text');

  $lists['price']['show'] = mosHTML :: RadioList($yesno, 'price_show', 'class="inputbox"',
    $realestatemanager_configuration['price']['show'], 'value', 'text');

	$lists['page']['items'] = '<input type="text" name="page_items"
    value="'.$realestatemanager_configuration['page']['items'].
    '" class="inputbox" size="3" maxlength="3" title="" />';
	
  //add for show in category picture
  $lists['cat_pic']['show'] = mosHTML :: RadioList($yesno, 'cat_pic_show', 'class="inputbox"',
    $realestatemanager_configuration['cat_pic']['show'], 'value', 'text');

  //add for show subcategory 
  $lists['subcategory']['show'] = mosHTML :: RadioList($yesno, 'subcategory_show', 'class="inputbox"',
    $realestatemanager_configuration['subcategory']['show'], 'value', 'text');

  //google Map key
  $lists['google_map']['key'] = '<input type="text" name="google_map_key" 
    value="'.$realestatemanager_configuration['google_map']['key'].
    '" class="inputbox" size="80" maxlength="200" title="" />';

    $view_type[]=mosHTML :: makeOption('0', _REALESTATE_MANAGER_CONFIG_VIEW_TYPE_LIST);
    $view_type[]=mosHTML :: makeOption('1', _REALESTATE_MANAGER_CONFIG_VIEW_TYPE_GALLERY);
    $view_type[]=mosHTML :: makeOption('2', _REALESTATE_MANAGER_CONFIG_VIEW_TYPE_LIST_GALLERY);
    $lists['view_type']=mosHTML::selectList($view_type, 'view_type',
                    'size="1" ', 'value', 'text', $realestatemanager_configuration['view_type']);
    
//configure_backend
  
	$lists['edocs']['allow'] = mosHTML :: RadioList($yesno, 'edocs_allow', 'class="inputbox"', $realestatemanager_configuration['edocs']['allow'], 'value', 'text');

	$lists['edocs']['location'] = '<input type="text" name="edocs_location" value="'.$realestatemanager_configuration['edocs']['location'].'" class="inputbox" size="50" maxlength="50" title="" disabled="disabled"/>';

	$lists['photos']['location'] = '<input type="text" name="photos_location" value="/components/com_realestatemanager/photos/" class="inputbox" size="50" maxlength="50" title="" disabled="disabled"/>';	

  //update
    $lists['update'] = mosHTML :: RadioList($yesno, 'update', 'class="inputbox"', $realestatemanager_configuration['update'], 'value', 'text');
    $txt = "";
   HTML_realestatemanager :: showConfiguration($lists, $option,$txt );
}

function rent($option, $bid) 
{
	//print_r($bid);exit;	
	global $database, $my;

	if (!is_array($bid) || count($bid) < 1) {
		echo "<script> alert('Select an item to rent'); window.history.go(-1);</script>\n";
		exit;
	}

	$bids = implode(',', $bid);
	
	$select ="SELECT a.*, cc.name AS category, l.id as rentid, l.rent_from as rent_from, ".
			"l.rent_return as rent_return, l.rent_until as rent_until, ".
			"l.user_name as user_name, l.user_email as user_email ".
			"\nFROM #__rem_houses AS a".
      "\nLEFT JOIN #__rem_categories as hc on hc.iditem = a.id".
			"\nLEFT JOIN #__rem_main_categories AS cc ON cc.id = hc.idcat".
			"\nLEFT JOIN #__rem_rent AS l ON l.id = a.fk_rentid".
			"\nWHERE a.id in (".$bids.")";
	$database->setQuery($select);
  

	if (!$database->query()) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit ();
	}

	$houses = $database->loadObjectList();

	//for rent or not
	$count=count($houses);
	for($i=0;$i<$count;$i++)
	{
		
		if($houses[$i]->listing_type != 'house for rent' && $houses[$i]->listing_type != 'room for rent' && $houses[$i]->listing_type != 'sublet')
		{
			?>
			
			<script type = "text/JavaScript" language = "JavaScript">
			alert('This house is not for rent');
        		window.history.go(-1);
			</script>
			<?php
			exit;
		}
	}
	// get list of categories

	$userlist[] = mosHTML :: makeOption('-1', '----------');	
	$database->setQuery("SELECT id AS value, name AS text from #__users ORDER BY name");
	$userlist = array_merge($userlist, $database->loadObjectList());
	$usermenu = mosHTML :: selectList($userlist, 'userid', 'class="inputbox" size="1"', 'value', 'text', '-1');
	
	HTML_realestatemanager :: showRentHouses($option, $houses, $usermenu, "rent");
}

///////////////////////////////////////////////////////////////////


function edit_rent($option, $bid) {   //print_r($bid);exit;
    global $database, $my;
    if (!is_array($bid) || count($bid) < 1) {
        echo "<script> alert('Select an item to rent'); window.history.go(-1);</script>\n";
        exit;
    }
    $bids = implode(',', $bid);

    //for databases without subselect
	$select ="SELECT a.*, cc.name AS category, l.id as rentid, l.rent_from as rent_from, ".
			"l.rent_return as rent_return, l.rent_until as rent_until, ".
			"l.user_name as user_name, l.user_email as user_email ".
			"\nFROM #__rem_houses AS a".
      "\nLEFT JOIN #__rem_categories as hc on hc.iditem = a.id".
			"\nLEFT JOIN #__rem_main_categories AS cc ON cc.id = hc.idcat".
			"\nLEFT JOIN #__rem_rent AS l ON l.id = a.fk_rentid".
			"\nWHERE a.id in (".$bids.")";

    $database->setQuery($select);

    if (!$database->query()) {
        echo "<script> alert('" . $database->getErrorMsg() . "'); window.history.go(-1); </script>\n";
        exit ();
    }

    $houses = $database->loadObjectList();
//print_r($houses);exit;
    $count = count($houses);
    for ($i = 0; $i < $count; $i++) {
     		if($houses[$i]->listing_type != 'house for rent' && $houses[$i]->listing_type != 'room for rent' && $houses[$i]->listing_type != 'sublet')
        {
?>
            <script type = "text/JavaScript" language = "JavaScript">
                alert('This house is not for rent');
                window.history.go(-1);
            </script>
<?php

            exit;
        }
    }
    for ($i = 0; $i < 1; $i++) {
        if ((($houses[$i]->rent_from) == '') && (($houses[$i]->rent_return) == '')) {
?>
            <script type = "text/JavaScript" language = "JavaScript">
                alert('You edit house that were not lent out');
                window.history.go(-1);
            </script>
<?php

            exit;
        }
    }
    // get list of users
    $userlist[] = mosHTML :: makeOption('-1', '----------');
    $database->setQuery("SELECT id AS value, name AS text from #__users ORDER BY name");
    $userlist = array_merge($userlist, $database->loadObjectList());
    $usermenu = mosHTML :: selectList($userlist, 'userid', 'class="inputbox" size="1"', 'value', 'text', '-1');

    HTML_realestatemanager :: showRentHouses($option, $houses, $usermenu, "edit_rent");
}


///////////////////////////////////////////////////////////////


function rent_return($option, $bid) 
{

  global $database, $my;
  if (!is_array($bid) || count($bid) < 1) {
    echo "<script> alert('Select an item to rent'); window.history.go(-1);</script>\n";
    exit;
  }
  $bids = implode(',', $bid);
  
    
    //exit;
  //for databases without subselect
	$select ="SELECT a.*, cc.name AS category, l.id as rentid, l.rent_from as rent_from, ".
			"l.rent_return as rent_return, l.rent_until as rent_until, ".
			"l.user_name as user_name, l.user_email as user_email ".
			"\nFROM #__rem_houses AS a".
      "\nLEFT JOIN #__rem_categories as hc on hc.iditem = a.id".
			"\nLEFT JOIN #__rem_main_categories AS cc ON cc.id = hc.idcat".
			"\nLEFT JOIN #__rem_rent AS l ON l.id = a.fk_rentid".
			"\nWHERE a.id in (".$bids.")";  
  $database->setQuery($select);
  
  if (!$database->query()) {
    echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
    exit ();
  }
  
  $houses = $database->loadObjectList();

  $count=count($houses);
  for($i=0;$i<$count;$i++)
   {
    if($houses[$i]->listing_type != 'house for rent' &&  $houses[$i]->listing_type != 'room for rent' && $houses[$i]->listing_type != 'sublet')
      {
       ?>
       <script type = "text/JavaScript" language = "JavaScript">
        alert('This house is not for rent');
        window.history.go(-1);
       </script>
       <?php
       exit;
      }
    }
    
  //print_r($houses);
      
  for($i=0;$i<1;$i++)
  {
    if((($houses[$i]->rent_from)=='')&&(($houses[$i]->rent_return)==''))
      {
      ?>
      <script type = "text/JavaScript" language = "JavaScript">
        alert('You cannot return houses that were not lent out');
        window.history.go(-1);
      </script>
      <?php 
      exit;         
      }
  }
  // get list of users
  $userlist[] = mosHTML :: makeOption('-1', '----------');	
  $database->setQuery("SELECT id AS value, name AS text from #__users ORDER BY name");
  $userlist = array_merge($userlist, $database->loadObjectList());
  $usermenu = mosHTML :: selectList($userlist, 'userid', 'class="inputbox" size="1"', 'value', 'text', '-1');

	HTML_realestatemanager :: showRentHouses($option, $houses, $usermenu, "rent_return");
}

function saveRent($option, $bids,$task="") {

  global $database;
  
  $checkh = mosGetParam($_POST, 'checkhouse');
  //print_r($l);exit;
  
  if($checkh != "on")
  {
    echo "<script> alert('Select an item to rent'); window.history.go(-1);</script>\n";
    exit;
  }
	
  $data = &JFactory::getDBO();
			
  $houseid = mosGetParam($_POST, 'houseid');
  $id = mosGetParam($_POST, 'id');	
    //print_r($houseid);exit;	
    
  $query ="SELECT * FROM #__rem_rent where fk_houseid= ".$id." AND rent_return is NULL ";
  $data->setQuery($query);
  $rentTerm = $data->loadObjectList();	

//print_r($rentTerm );
  if (!is_array($bids) || count($bids) < 1) {
    echo "<script> alert('Select an item to rent'); window.history.go(-1);</script>\n";
    exit;
  }

	$rent = new mosRealEstateManager_rent($database);
  if($task == "edit_rent") $rent->load( $bids[0] ) ;

  $rent_from=mosGetParam($_POST, 'rent_from');
  $rent_until=mosGetParam($_POST, 'rent_until');
  
  if($rent_from >$rent_until)
  {
    echo "<script> alert('".$rent_from." more then ".$rent_until."'); window.history.go(-1); </script>\n";
    exit ();
  }

  $rent_from=substr($rent_from, 0, 10);
  $rent_until=substr($rent_until, 0, 10);
  
  //print_r($rentTerm);exit;
  if(isset($rentTerm[0]))
  {
  
    for ($e = 0, $m = count($rentTerm); $e < $m;$e++){
      if($task == "edit_rent" && $bids[0] == $rentTerm[$e]->id ) continue;
      
      $rentTerm[$e]->rent_from= substr($rentTerm[$e]->rent_from, 0, 10);
      $rentTerm[$e]->rent_until= substr($rentTerm[$e]->rent_until, 0, 10);
          //Rent check
      if(( $rent_from >=$rentTerm[$e]->rent_from &&
        $rent_from<=$rentTerm[$e]->rent_until)||
          ($rent_from<=$rentTerm[$e]->rent_from
          && $rent_until>=$rentTerm[$e]->rent_until)
          ||( $rent_until >=$rentTerm[$e]->rent_from && $rent_until<=$rentTerm[$e]->rent_until) )
      {
        echo "<script> alert('Sorry , this object already rent out from ".
			$rentTerm[$e]->rent_from." to ".$rentTerm[$e]->rent_until."'); window.history.go(-1); </script>\n";
            exit ();
      }
    }
  }
		
  if (mosGetParam($_POST, 'rent_from') != "" ) 
  {
    $rent->rent_from = mosGetParam($_POST, 'rent_from');

  } else {
    $rent->rent_from = null;
  }

  if (mosGetParam($_POST, 'rent_until') != "")
  {
    $rent->rent_until = mosGetParam($_POST, 'rent_until');

  } else {
    $rent->rent_until = null;
  }
    
    $rent->fk_houseid = $id;
    $userid = mosGetParam($_POST, 'userid');
  
    if ($userid == "-1") {
      $rent->user_name = mosGetParam($_POST, 'user_name', '');
      $rent->user_email = mosGetParam($_POST, 'user_email', '');
    } else {
      $rent->getRentTo( intval($userid) );
    }
  
    if (!$rent->check($rent)) {
      echo "<script> alert('".$rent->getError()."'); window.history.go(-1); </script>\n";
      exit ();
    }
  
  
  
    if (!$rent->store()) {
      echo "<script> alert('".$rent->getError()."'); window.history.go(-1); </script>\n";
      exit ();
    }
    
    $rent->checkin();
    $house = new mosRealEstateManager($database);
    $house->load($id);		
    $house->fk_rentid = $rent->id;
    $house->store();

    $house->checkin();

	//}
	mosRedirect("index.php?option=$option");

}


function saveRent_return($option, $lids) {
//print_r($lids);exit;
  global $database, $my;
    
  //print_r($lids);exit;
  if (!is_array($lids) || count($lids) < 1||$lids[0]==0) {
    echo "<script> alert('Select an item to return'); window.history.go(-1);</script>\n";
    exit;
  }
  //print_r($lids);exit;	
    
  for ($i = 0, $n = count($lids); $i < $n; $i ++) {
    $houseid = mosGetParam($_POST, 'houseid');
    $id = mosGetParam($_POST, 'id');
    
    //print_r($houseid);  echo  "<br /><br />";exit;
  
    $rent = new mosRealEstateManager_rent($database);
    $rent->load($lids[$i]);
    if($rent->rent_return != null )	
    {
      echo "<script> alert('  House already returned'); window.history.go(-1);</script>\n";
      exit;
    }	
      
    $rent->rent_return = date("Y-m-d H:i:s");
  
    
    
    if (!$rent->check($rent)) {
      echo "<script> alert('".$rent->getError()."'); window.history.go(-1); </script>\n";
      exit ();
    }
  
    if (!$rent->store()) {
      echo "<script> alert('".$rent->getError()."'); window.history.go(-1); </script>\n";
      exit ();
    }
  
     // print_r($rent);exit;
    $rent->checkin();
    
    $is_update_house_lend = true;
    if($is_update_house_lend) {

      $house = new mosRealEstateManager($database);
      $house->load($id);	
    
        
      $query ="SELECT * FROM #__rem_rent where fk_houseid= ".$id." AND rent_return is NULL ";
      $database->setQuery($query);
      $info_rents = $database->loadObjectList();	
      //print_r($info_rents);exit;
      if(isset($info_rents[0])){
        $house->fk_rentid =$info_rents[0]->id;
        $is_update_house_lend = FALSE;
      }else{
        $house->fk_rentid = 0;
      }
          
      $house->store(true);
      $house->checkin(true);
    }  
	}
	mosRedirect("index.php?option=$option");
}
